// 导入 Cannon.js
import * as Cannon from 'cannon';

// 创建 Cannon.js 的世界对象
const world = new Cannon.World();
world.gravity.set(0, 0, -9.82); // 设置重力

// 创建地面
const groundShape = new Cannon.Plane();
const groundBody = new Cannon.Body({ mass: 0 });
groundBody.addShape(groundShape);
world.addBody(groundBody);

// 创建小车的车身
const chassisShape = new Cannon.Box(new Cannon.Vec3(1, 0.5, 0.2));
const chassisBody = new Cannon.Body({ mass: 1 });
chassisBody.addShape(chassisShape);
chassisBody.position.set(0, 0, 1);
world.addBody(chassisBody);

// 创建车轮
const wheelRadius = 0.2;
const wheelHalfWidth = 0.1;
const wheelHalfDepth = 0.1;

const wheelPositions = [
  [-0.5, -0.5],
  [0.5, -0.5],
  [-0.5, 0.5],
  [0.5, 0.5],
];

const wheelBodies = [];

for (const position of wheelPositions) {
  const wheelShape = new Cannon.Cylinder(wheelRadius, wheelRadius, wheelHalfDepth, 20);
  const wheelBody = new Cannon.Body({ mass: 0.2 });
  wheelBody.addShape(wheelShape);
  wheelBody.position.set(position[0], position[1], 0.6);
  world.addBody(wheelBody);
  wheelBodies.push(wheelBody);
}

// 创建约束，将车轮连接到车身上
const wheelConstraints = [];

for (const wheelBody of wheelBodies) {
  const wheelConstraint = new Cannon.HingeConstraint(chassisBody, wheelBody, {
    pivotA: new Cannon.Vec3(wheelBody.position.x, wheelBody.position.y, 0.6),
    axisA: new Cannon.Vec3(0, 1, 0),
  });
  world.addConstraint(wheelConstraint);
  wheelConstraints.push(wheelConstraint);
}

// 键盘控制
const keyState:any = {};

document.addEventListener('keydown', (event) => {
  keyState[event.code] = true;
});

document.addEventListener('keyup', (event) => {
  keyState[event.code] = false;
});

// 创建渲染器和场景
const renderer = new Cannon.Renderer();
const scene = new Cannon.Scene();
scene.addRenderable(chassisBody, renderer);
for (const wheelBody of wheelBodies) {
  scene.addRenderable(wheelBody, renderer);
}

// 更新场景
function animate() {
  requestAnimationFrame(animate);

  // 处理键盘控制
  const speed = 5;

  if (keyState['KeyW']) {
    chassisBody.position.x += speed * Math.sin(chassisBody.angle);
    chassisBody.position.y -= speed * Math.cos(chassisBody.angle);
  }

  if (keyState['KeyS']) {
    chassisBody.position.x -= speed * Math.sin(chassisBody.angle);
    chassisBody.position.y += speed * Math.cos(chassisBody.angle);
  }

  world.step(1 / 60);
  renderer.render(scene, world);
}
animate();